// 云函数入口文件
const cloud = require('wx-server-sdk')
const {getDateByStamp}=require('./date.js')

cloud.init()
const db=cloud.database()
const _=db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let openid =wxContext.OPENID;
  const{weRunData,userData}=event;
  let time= weRunData.data.stepInfoList[30].timestamp;
  let list = weRunData.data.stepInfoList;
  let w=Number(getDateByStamp('w',time+3600*8)); //星期数
  if(w==0){w=7;}
  let d=Number(getDateByStamp('d',time+3600*8)); //几号

  //获取当天步数
  dayData=list[30].step;

  //获取本周步数
  let weekData={};
  let ws=0;
  let wl=[];
  for(let i=30;i>30-w;i--){
    let obj=new Object();
    obj.weekday=w-(30-i);
    obj.step=list[i].step;
    wl.unshift(obj);
    ws+=list[i].step;
  }
  weekData.ws=ws;
  weekData.wl=wl;

  //获取本月步数
  let monthData={};
  let ms=0;
  let ml=[];
  for(let i=0;i<d;i++){
    let obj=new Object();
    obj.mday=d-i;
    obj.step=list[30-i].step;
    ml.unshift(obj);
    ms+=list[30-i].step;
  }
  monthData.ms=ms;
  monthData.ml=ml;

  //判断是不是新用户
  let proCount = await db.collection('stepPhb').where({
    openid
  }).count();
  if(proCount.total==0){
    //新用户初始化日榜、周榜、月榜数据
    await db.collection('stepPhb').add({
      data:{
        openid,
        userData:userData.data,
        dayData,
        weekData,
        monthData,
        dup:[], //日点赞
        wup:[], //周点赞
        mup:[]  //月点赞
      }
    })
  }

  

  else{
    await db.collection('stepPhb').where({
      openid
    }).update({
      data:{
        userData: userData.data,
        dayData,
        weekData,
        monthData
      }
    })
  }

  let proCount2 = await db.collection('giftPhb').where({
    openid
  }).count();
  if (proCount2.total == 0) {
    //新用户初始化日榜、周榜、月榜数据
    await db.collection('giftPhb').add({
      data: {
        openid,
        userData: userData.data,
        newReceive: [],
        allReceive: {},
        meiLi: 0,
        dayRec: 0,
        weekRec: 0,
        monthRec: 0,
        dup: [],
        wup: [],
        mup: []
      }
    })
  }
}